package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/check")
    public Result check(HttpServletResponse response, @RequestBody Map map){
        //获取到map的数据
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        //获取到redis中保存的验证码信息
        Jedis resource = jedisPool.getResource();
        String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        resource.close();

        //进行验证码的判断
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)){
            //根据手机号码获取到对应的用户数据
            Member member = memberService.findByTelephone(telephone);
            if (member == null){
                //表示的是这个用户没有创建,需要创建一个member对象进行封装操作
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                //新添加一个
                memberService.add(member);
            }
            //将获取到的member对象封装为Json数据
            String json = JSON.toJSON(member).toString();

            //如果不为空表示已经有这个用户
            Cookie cookie = new Cookie("telephone_login", telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);

            //将member对象保存到Redis中
            Jedis resource1 = jedisPool.getResource();
            //设置5分钟有效期限
            resource1.setex(telephone,60*5,json);
            resource1.close();
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
